from datetime import date

from peewee import *

# 连接数据库
db = SqliteDatabase('people.db')


# 创建模型
class Person(Model):
    name = CharField()
    birthday = DateField()

    class Meta:
        database = db  # This model uses the "people.db" database.


class Pet(Model):
    owner = ForeignKeyField(Person, backref='pets')
    name = CharField()
    animal_type = CharField()

    class Meta:
        database = db  # this model uses the "people.db" database


# 创建表
db.connect()
db.create_tables([Person, Pet])

"""
Usually this type of duplication is undesirable. 
通常这种类型的复制是不受欢迎的。

To accommodate the more common (and intuitive) workflow of listing a person and attaching a list of that person’s pets, we can use a special method called prefetch():
为了适应更常见(也更直观)的工作流程，即列出一个人并附上此人的宠物列表，我们可以使用一个特殊的方法prefetch():
"""
# prefetch(Pet) 将外键转换为一个序列，并可以通过对象.外键名小写+s访问
# 比如外键Pet，通过.prefetch(Pet)，转换为pets
query = Person.select().order_by(Person.name).prefetch(Pet)
for person in query:
    print(person.name)
    for pet in person.pets:
        print('  *', pet.name)
